package com.littleken.foodieService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.google.common.collect.Lists;
import com.littleken.foodieCommon.Response.ErrorCode;
import com.littleken.foodieCommon.Response.ServerResponse;
import com.littleken.foodieCommon.Utils.BeanCopierUtil;
import com.littleken.foodieCommon.Utils.MD5Utils;
import com.littleken.foodieCommon.constant.Constant;
import com.littleken.foodieMapper.UsersMapper;
import com.littleken.foodiePojo.bo.InsertUserBO;
import com.littleken.foodiePojo.domain.UsersDO;
import com.littleken.foodiePojo.enums.SexEnum;
import com.littleken.foodiePojo.vo.UsersVO;
import com.littleken.foodieService.UsersService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.List;

/*
 * Create by littleken on 2020/11/20 17:33
 */
@Service
public class UsersServiceImpl implements UsersService {

    private static final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class);

    @Resource
    private UsersMapper usersMapper;

    @Override
    public List<UsersDO> userList() {
        List<com.littleken.foodiePojo.domain.UsersDO> usersDOS = Lists.newArrayList();
        usersDOS = usersMapper.selectList(new QueryWrapper<>());
        return usersDOS;
    }

    @Override
    public UsersDO getUser(String id) {
        return usersMapper.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse insertUser(InsertUserBO insertUserBO) {
        String userId = null;

        //用户名判重
        if (queryUserNameIsExist(insertUserBO.getUsername())) {
            return ServerResponse.fail(ErrorCode.USER_IS_EXIST);
        }

        //两次密码判是否相同
        if (!insertUserBO.getPassword().equals(insertUserBO.getConfirmPassword())) {
            return ServerResponse.fail(ErrorCode.PASSWORD_NOT_EQUALS);
        }

        UsersDO usersDO = new UsersDO();
        try {
            usersDO.setUsername(insertUserBO.getUsername());
            usersDO.setNickname(insertUserBO.getUsername());
            usersDO.setPassword(MD5Utils.getMD5Str(insertUserBO.getPassword()));
            usersDO.setBirthday(LocalDate.parse("1900-01-01"));
            usersDO.setSex(SexEnum.SEX_UNKNOW.getCode());
            usersDO.setCreatedTime(LocalDate.now());
            usersDO.setUpdatedTime(LocalDate.now());
            usersDO.setFace(Constant.DEFAULT_FACE);
            usersMapper.insert(usersDO);
            userId = usersDO.getId();
        } catch (NoSuchAlgorithmException e) {
            logger.debug("密码加密失败");
            usersDO.setPassword(insertUserBO.getPassword());
            usersMapper.insert(usersDO);
            userId = usersDO.getId();
        } catch (Exception e) {
            logger.debug("新增失败");
        }
        return StringUtils.isNotBlank(userId) ?
                ServerResponse.success(userId) :
                ServerResponse.fail(ErrorCode.SQL_EXECUTE_ERR);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateUser(UsersDO usersDO) {
        usersDO.setUpdatedTime(LocalDate.now());
        int i = usersMapper.updateById(usersDO);
        return i == 1 ? usersDO.getId() : null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse deleteUser(String id) {
        com.littleken.foodiePojo.domain.UsersDO usersDO = usersMapper.selectById(id);
        if (usersDO == null) {
            return ServerResponse.fail(ErrorCode.RECORD_NOT_EXIST);
        }
        int i = usersMapper.deleteById(id);
        return i == 1 ? ServerResponse.success() : ServerResponse.fail();
    }

    /**
     * 用户名是否存在
     *
     * @return 存在true 不存在false
     */
    @Override
    public boolean queryUserNameIsExist(String userName) {
        QueryWrapper<com.littleken.foodiePojo.domain.UsersDO> wrapper = new QueryWrapper();
        wrapper.eq("username", userName);
        Integer result = usersMapper.selectCount(wrapper);
        return result > 0 ? true : false;
    }

    @Override
    public UsersVO userLogin(String userName, String password) {
        UsersVO usersVO = null;
        try {
            password = MD5Utils.getMD5Str(password);
        } catch (NoSuchAlgorithmException e) {
            logger.debug("密码加密错误");
        }
        QueryWrapper<UsersDO> wrapper = new QueryWrapper<>();
        wrapper.eq("username", userName);
        wrapper.eq("password", password);
        UsersDO usersDO = usersMapper.selectOne(wrapper);
        usersVO = BeanCopierUtil.copy(usersDO, UsersVO.class);
        return usersVO;
    }

}
